<template>
  <div class="pt-4 pb-6">
    <div class="container">
      <p style="text-align: center">金华市体育运动学校射击训练基地</p>
      <van-swipe
        :autoplay="3000"
        indicator-color="white"
        height="400"
        class="mx-2 my-4"
        style="border-radius: 10px"
      >
        <van-swipe-item v-for="item in List">
          <van-image style="height: 100%; width: 100%" lazy-load :src="item" />
        </van-swipe-item>
      </van-swipe>
      <van-form @submit="onSubmit" ref="formInstance" label-width="80">
        <van-cell-group inset>
          <van-field
            v-model="form.parName"
            name="parName"
            label="家长姓名"
            placeholder="请填写家长姓名"
            required
            :rules="[{ required: true, message: '请填写家长姓名' }]"
          />
          <van-field
            v-model="form.name"
            name="name"
            label="孩子姓名"
            required
            placeholder="请填写孩子姓名"
            :rules="[{ required: true, message: '请填写孩子姓名' }]"
          />
          <van-field
            v-model="form.sex"
            name="sex"
            label="性别"
            placeholder="请选择性别"
            required
            readonly
            @click="onClick('sex')"
            :rules="[{ required: true, message: '请选择性别' }]"
          >
          </van-field>
          <van-field
            v-model="form.birthday"
            name="birthday"
            label="出生年月"
            required
            readonly
            @click="onClick('birthday')"
            placeholder="请选择出生年月"
            :rules="[{ required: true, message: '请选择出生年月' }]"
          />
          <van-field
            v-model="form.mobile"
            name="mobile"
            label="手机号"
            placeholder="请输入手机号"
            required
            type="number"
            maxlength="11"
            :rules="[
              {
                required: true,
                message: '请输入手机号或者手机号有误',
                pattern:
                  /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/,
              },
            ]"
          />
          <van-field
            v-model="form.height"
            name="height"
            label="身高"
            required
            placeholder="请输入身高"
            type="number"
            :rules="[{ required: true, message: '请输入身高' }]"
          >
            <template #extra>cm</template></van-field
          >
          <van-field
            v-model="form.weight"
            name="weight"
            label="体重"
            placeholder="请输入体重"
            type="number"
            required
            :rules="[{ required: true, message: '请输入体重' }]"
          >
            <template #extra>kg</template></van-field
          >
          <van-field
            v-model="form.birthPlaceName"
            name="birthPlaceName"
            label="籍贯"
            readonly
            required
            placeholder="请选择籍贯"
            @click="onClick('birthPlace')"
            :rules="[{ required: true, message: '请选择籍贯' }]"
          />
          <van-field
            v-model="form.sportsExperience"
            name="sportsExperience"
            label="运动经历"
            show-word-limit
            required
            readonly
            @click="showCascader = true"
            placeholder="请选择是否学习训练过以下运动"
            :rules="[
              { required: true, message: '请选择是否学习训练过以下运动' },
            ]"
          >
          </van-field>
          <van-field
            v-model="form.characteristic"
            name="characteristic"
            label="性格特征"
            required
            placeholder="请选择性格特征"
            readonly
            @click="showCascader1 = true"
            :rules="[{ required: true, message: '请选择性格特征' }]"
          />
          <van-field
            v-model="form.parSportsExperience"
            name="parSportsExperience"
            label="父母运动背景"
            required
            readonly
            @click="
              () => {
                (showCascader = true), (isPar = true);
              }
            "
            placeholder="请选择是否学习训练过以下运动"
            :rules="[
              { required: true, message: '请选择是否学习训练过以下运动' },
            ]"
          >
          </van-field>
          <van-field
            v-model="form.idPhoto"
            name="idPhoto"
            label="照片上传"
            placeholder="请上传照片"
            readonly
          >
            <template #input>
              <van-uploader
                :before-read="useCompressor"
                :max-count="4"
                multiple
                v-model="fileList"
              /> </template
          ></van-field>
        </van-cell-group>
        <p class="text-center">
          报名系统电话咨询：
          <a
            class="py-2"
            style="color: rgb(41, 121, 255)"
            href="tel:0579-82382999"
            >0579-82382999</a
          >
        </p>
        <div style="margin: 16px">
          <van-button
            :loading="loading"
            round
            block
            type="primary"
            native-type="submit"
          >
            确认提交
          </van-button>
        </div>
      </van-form>
      <van-popup round v-model:show="showPicker" position="bottom">
        <van-area
          v-if="isBirthPlace"
          @confirm="onConfirm"
          title="籍贯"
          :area-list="areaList"
          v-model="form.birthPlace"
          @cancel="showPicker = false"
        />
        <van-picker
          :columns="columnsValue"
          @confirm="onConfirm"
          @cancel="showPicker = false"
          v-else
        />
      </van-popup>
      <van-popup round v-model:show="showDatePicker" position="bottom">
        <van-date-picker
          v-model="currentDate"
          title="选择年月"
          :columnsType="['year', 'month']"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="onConfirm"
          @cancel="showDatePicker = false"
        />
      </van-popup>
      <van-popup
        round
        v-model:show="showCascader1"
        position="bottom"
        @close="onClose"
      >
        <BaseCascader
          label="请选择性格特征"
          @on-close="showCascader1 = false"
          @on-submit="
            () => {
              form.characteristic = options1
                .filter((item) => item.checked)
                .map((item) => item.text)
                .join('、');
              showCascader1 = false;
            }
          "
          :options="options1"
          :needSub="false"
        ></BaseCascader>
      </van-popup>
      <van-popup
        round
        v-model:show="showCascader"
        position="bottom"
        @close="onClose"
      >
        <BaseCascader
          label="是否学习训练过以下运动"
          @on-close="showCascader = false"
          @on-submit="handleSubmit"
          v-if="showCascader"
          :options="options"
        ></BaseCascader>
      </van-popup>
    </div>
    <div v-html="editorContent"></div>
  </div>
</template>

<script setup lang="ts">
import { useCompressor } from "@/utils";
import type { PickerConfirmEventParams } from "vant";
import { areaList } from "@vant/area-data";
import BaseCascader from "@/components/BaseCascader.vue";
import { showSuccessToast } from "vant";
import { submit, fileUpload, getContent, getSwipe } from "@/api/index";
const sexOption = [
  {
    value: "男",
    text: "男",
  },
  {
    value: "女",
    text: "女",
  },
];
const getImageUrl = (name: string | number, type = "jpg") => {
  return new URL(`../assets/${name + "." + type}`, import.meta.url).href;
};
const options1 = ref([
  {
    text: "活泼开朗",
    value: "活泼开朗",
  },
  {
    text: "沉默内向",
    value: "沉默内向",
  },
  {
    text: "勇敢果断",
    value: "勇敢果断",
  },
  {
    text: "情绪稳定",
    value: "情绪稳定",
  },
  {
    text: "情绪较为浮躁没有耐心",
    value: "情绪较为浮躁没有耐心",
  },
  {
    text: "专注力好",
    value: "专注力好",
  },
  {
    text: "不能长时间专注思维发散",
    value: "不能长时间专注思维发散",
  },
  {
    text: "记忆力强",
    value: "记忆力强",
  },
  {
    text: "粗心大意",
    value: "粗心大意",
  },
]);
const options = ref([
  {
    text: "球类运动",
    value: "球类运动",
    children: [
      { text: "篮球", value: "篮球" },
      { text: "足球", value: "足球" },
      { text: "网球", value: "网球" },
      { text: "羽毛球", value: "羽毛球" },
      { text: "乒乓球", value: "乒乓球" },
      { text: "高尔夫", value: "高尔夫" },
      { text: "棒球", value: "棒球" },
      { text: "曲棍球", value: "曲棍球" },
      { text: "橄榄球", value: "橄榄球" },
      { text: "冰球", value: "冰球" },
    ],
  },
  {
    text: "射击运动",
    value: "射击运动",
    children: [
      { text: "十米气步枪", value: "十米气步枪" },
      { text: "十米气手枪", value: "十米气手枪" },
      { text: "飞碟射击", value: "飞碟射击" },
      { text: "移动靶", value: "移动靶" },
    ],
  },
  {
    text: "体操类运动",
    value: "体操类运动",
    children: [
      { text: "艺术体操", value: "艺术体操" },
      { text: "竞技体操", value: "竞技体操" },
      { text: "蹦床体操", value: "蹦床体操" },
      { text: "体操操", value: "体操操" },
      { text: "口技体操", value: "口技体操" },
      { text: "体操轮", value: "体操轮" },
      { text: "空中曲棍球", value: "空中曲棍球" },
    ],
  },
  {
    text: "田径类运动",
    value: "田径类运动",

    children: [
      { text: "短跑", value: "短跑" },
      { text: "中跑", value: "中跑" },
      { text: "长跑", value: "长跑" },
      { text: "跳高", value: "跳高" },
      { text: "跳远", value: "跳远" },
      { text: "三级跳远", value: "三级跳远" },
      { text: "铅球", value: "铅球" },
      { text: "标枪", value: "标枪" },
      { text: "十项全能", value: "十项全能" },
      { text: "七项全能", value: "七项全能" },
    ],
  },
  {
    text: "武术类运动",
    value: "武术类运动",

    children: [
      { text: "太极拳", value: "太极拳" },
      { text: "空手道", value: "空手道" },
      { text: "柔道", value: "柔道" },
      { text: "跆拳道", value: "跆拳道" },
      { text: "功夫", value: "功夫" },
      { text: "剑术", value: "剑术" },
      { text: "武术套路", value: "武术套路" },
      { text: "拳击", value: "拳击" },
      { text: "散打", value: "散打" },
      { text: "西洋剑术", value: "西洋剑术" },
    ],
  },
  {
    text: "特殊运动",
    value: "特殊运动",

    children: [
      { text: "马术", value: "马术" },
      { text: "冰壶", value: "冰壶" },
      { text: "曲棍球", value: "曲棍球" },
      { text: "飞镖", value: "飞镖" },
      { text: "冰壁攀岩", value: "冰壁攀岩" },
      { text: "蹦床", value: "蹦床" },
      { text: "滑板运动", value: "滑板运动" },
      { text: "空中曲棍球", value: "空中曲棍球" },
      { text: "泳池障碍赛", value: "泳池障碍赛" },
      { text: "极限运动", value: "极限运动" },
    ],
  },
  {
    text: "其他",
    value: "其他",
  },
]);
const List = [
  getImageUrl(1),
  getImageUrl(2),
  getImageUrl(3),
  getImageUrl(4),
  getImageUrl(5),
  getImageUrl(6),
];
const fileList = ref([]),
  showCascader1 = ref(false),
  editorContent = ref(""),
  currentDate = ref([]),
  showCascader = ref(false);
// const List = ref<string[]>([]);
// getSwipe().then(({ list }) => {
//   List.value = list;
// });
// 在页面加载完成后将滚动位置重置到顶部
getContent().then(({ content }) => {
  editorContent.value = content;
});
const setCheckedFalse = (data) => {
  if (Array.isArray(data)) {
    // 如果是数组，遍历数组的每一项
    data.forEach((item) => {
      // 递归调用函数处理每一项
      setCheckedFalse(item);
    });
  } else if (typeof data === "object" && data !== null) {
    // 如果是对象，遍历对象的每一个属性
    for (const key in data) {
      if (Object.prototype.hasOwnProperty.call(data, key)) {
        // 递归调用函数处理属性值
        setCheckedFalse(data[key]);
      }
    }
    // 设置 checked 属性为 false
    if ("checked" in data) {
      data.checked = false;
    }
  }
};
const getCheckedValues = (data) => {
  const checkedValues = [];

  const traverse = (obj) => {
    if (Array.isArray(obj)) {
      obj.forEach((item) => {
        traverse(item);
      });
    } else if (typeof obj === "object" && obj !== null) {
      for (const key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
          traverse(obj[key]);
        }
      }
      if ("checked" in obj && obj.checked === true) {
        checkedValues.push(obj.value); // 将符合条件的值添加到数组中
      }
    }
  };

  traverse(data);

  return checkedValues;
};

const isPar = ref(false);
// 调用函数设置 options 对象的 checked 属性为 false

const form = reactive<Record<string, any>>({
    birthPlace: "330702",
    birthPlaceName: "",
  }),
  showPicker = ref(false),
  formInstance = ref(null),
  showDatePicker = ref(false),
  minDate = new Date(1990, 0, 1),
  maxDate = new Date(2025, 5, 1),
  loading = ref(false);
const columnsType = ref("");
const columnsValue = computed(() => {
  return sexOption;
});
const isBirthPlace = ref(false);
const onSubmit = async () => {
    loading.value = true;
    const { birthPlace, ...rest } = form;
    let fileStringList = [];
    for (let p of fileList.value) {
      const data = await fileUpload(p.file);
      fileStringList.push(data);
    }
    submit({
      ...rest,
      photo: fileStringList.join(","),
    })
      .then(() => {
        loading.value = false;
        showSuccessToast("提交成功");
        setTimeout(() => {
          location.reload();
        }, 2000);
      })
      .catch(() => {
        loading.value = false;
      });
  },
  onConfirm = ({
    selectedValues,
    selectedOptions,
  }: PickerConfirmEventParams) => {
    if (isBirthPlace.value) {
      form.birthPlaceName = selectedOptions.map((item) => item?.text).join("");
    } else if (showDatePicker.value) {
      form.birthday = selectedValues.join("/");
    } else {
      form[columnsType.value] = selectedValues[0];
    }
    showPicker.value = false;
    showDatePicker.value = false;
  },
  onClick = (type: string) => {
    if (type === "birthPlace") {
      isBirthPlace.value = true;
      showPicker.value = true;
    } else if (type === "birthday") {
      showDatePicker.value = true;
      isBirthPlace.value = false;
    } else {
      columnsType.value = type;
      showPicker.value = true;
      isBirthPlace.value = false;
    }
  },
  onClose = () => {
    isPar.value = false;
    setCheckedFalse(options1.value);
    setCheckedFalse(options.value);
  },
  handleSubmit = () => {
    const selectedValues = getCheckedValues(options.value).join("、");
    if (isPar.value) {
      form.parSportsExperience = selectedValues;
    } else {
      form.sportsExperience = selectedValues;
    }
    showCascader.value = false;
  };
</script>
<script lang="ts">
export default {
  name: "home",
};
</script>

<style lang="scss" scoped>
.container {
  background-color: #fff;
  height: 100%;
}
:deep(.van-cell-group) {
  margin: 20px 10px 0 10px;
  .van-field__control {
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
}
</style>
